package recipese.controller;

import javax.servlet.RequestDispatcher;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

@SuppressWarnings("serial")
public abstract class BaseServlet extends HttpServlet {
	
	private static final Logger log = LoggerFactory.getLogger(BaseServlet.class);
	
	protected WebApplicationContext context;
	
	@Override
	public void init() throws ServletException {
		this.context = WebApplicationContextUtils.getWebApplicationContext(this.getServletContext());
	}

	/**
	 * Forwards request and response to given path. Handles any exceptions
	 * caused by forward target by printing them to logger.
	 * 
	 * @param request 
	 * @param response
	 * @param path 
	 */
	protected void forward(HttpServletRequest request, HttpServletResponse response, String path) {
		try {
			RequestDispatcher dispatcher = request.getRequestDispatcher(path);
			dispatcher.forward(request, response);
		} catch (Throwable tr) {
			log.error("Cought Exception: " + tr.getMessage());
			log.debug("StackTrace:", tr);
		}
	}
	
}
